#include <iostream>

#include "CnfSvrClient.h"
#include "ProtoHelper.h"
#include "CnfSvrClientProtoHelper.h"
#include "CnfSvrCommon.h"

using std::cout;
using std::endl;

LoggerPtr CnfSvrClient::_logger = Logger::getLogger("CnfSvrClient");

int CnfSvrClient::init(const char * svr_ip, const unsigned svr_port, const int conn_pool_size, const int conn_timeout, \
			const int send_timeout,  const int recv_timeout, const int max_response_size) {
	if (NULL == svr_ip  || svr_port < 0 || conn_pool_size < 1) {
		LOG4CXX_ERROR(_logger, "init error, invalid args");
		return -1;
	}
	_svr_ip = svr_ip;
	_svr_port = svr_port;
	_conn_pool_size = conn_pool_size;
	_conn_timeout = conn_timeout;
	_send_timeout = send_timeout;
	_recv_timeout = recv_timeout;
	_max_response_size = max_response_size;
	int ret = _pool.init(svr_ip, svr_port, conn_timeout, conn_pool_size);
	if (ret < 0) {
		LOG4CXX_ERROR(_logger, "conn pool init error, ret:" << ret << ", svr_ip:" << svr_ip << ", svr_port:" << \
				svr_port << ", conn_timeout:" << conn_timeout << ", conn_pool_size:" << conn_pool_size);
		return -2;
	}
	LOG4CXX_INFO(_logger, "CnfSvrClient init ok, svr_ip:" << svr_ip << ", svr_port:" << svr_port << ", conn_timeout:" << \
			conn_timeout << ", conn_pool_size:" << ", send_timeout:" << send_timeout << ", recv_timeout:" << \
			recv_timeout);
	return 1;
}

int CnfSvrClient::get_all_cnf(NS_CNF & ns, list<MDS_CNF> & l_mds, list<DS_CNF> & l_ds)	{
	LOG4CXX_DEBUG(_logger, __FUNCTION__ << ", begin");
	SocketConnPtr cp;
	int ret = _pool.get(cp);
	if (ret < 0) {
		LOG4CXX_ERROR(_logger, "in get all cnf, could not get connection from pool");
		return -1;
	}
	string request = cs_build_request_get_all_cnf();
	string response;
	ret = send_and_recv_cmd(cp, _send_timeout, _recv_timeout, request.c_str(), request.size(), _max_response_size, response);
	if (ret < 0) {
		LOG4CXX_ERROR(_logger, "in get all cnf, send and recv cmd error, ret:" << ret);
		return -2;
	}
	int result;
	ret = cs_parse_response_get_all_cnf(response.c_str(), result, ns, l_mds, l_ds);
	LOG4CXX_DEBUG(_logger, __FUNCTION__ << ", end, ret:" << ret);
	if (ret < 0) return CS_ERR_INVALID_RESPONSE;
	return result;
}

int CnfSvrClient::get_ns_cnf(NS_CNF & ns) {
	list<MDS_CNF> l_mds;
	list<DS_CNF> l_ds;
	int ret = get_all_cnf(ns, l_mds, l_ds);
	return ret;

}

int CnfSvrClient::get_all_mds_cnf(list<MDS_CNF> & l_mds) {
	NS_CNF ns;
	list<DS_CNF> l_ds;
	int ret = get_all_cnf(ns, l_mds, l_ds);
	return ret;


}

int CnfSvrClient::get_all_ds_cnf(list<DS_CNF> & l_ds) {
	NS_CNF ns;
	list<MDS_CNF> l_mds;
	int ret = get_all_cnf(ns, l_mds, l_ds);
	return ret;
}
